import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/15 10:22
 * @description 用标志反转线性链表list
 */
public class Solution {
    public static void main(String[] args) {

    }
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean reverse = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                temp.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            if (!reverse) {
                ans.add(temp);
            }else {
                List<Integer> list = new ArrayList<>();
                for (int i = temp.size() - 1; i >= 0; i--) {
                    list.add(temp.get(i));
                }
                ans.add(list);
            }
            reverse = !reverse;
        }
        return ans;
    }
}
